package org.skydiveapp2;

import java.text.MessageFormat;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.data.LogbookHistory;
import org.skydiveapplibrary.data.Settings;
import org.skydiveapplibrary.data.UnitOfMeasure;
import org.skydiveapplibrary.repository.LogbookHistoryRepository;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.ui.FormatUtility;
import org.skydiveapplibrary.ui.FreefallTimeDialog;
import org.skydiveapplibrary.ui.NumberDialog;
import org.skydiveapplibrary.ui.FreefallTimeDialog.OnFreefallTimeSetListener;
import org.skydiveapplibrary.ui.NumberDialog.OnNumberSetListener;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SettingsActivity extends Activity
{
	// repositories
	private LogbookHistoryRepository historyRepository = new LogbookHistoryRepository(this);
	private SettingsRepository settingsRepository = new SettingsRepository(this);
	
	// listeners
	private OnClickListener freefallTimeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showFreefallTimeDialog();
		}
	};
	private OnClickListener cutawayEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showCutawayDialog();
		}
	};
	private OnClickListener exitAltitudeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showExitAltitudeDialog();
		}
	};
	private OnClickListener deploymentAltitudeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showDeploymentAltitudeDialog();
		}
	};

	private OnFreefallTimeSetListener freefallTimeSetListener = new OnFreefallTimeSetListener()
	{
		@Override
		public void onFreefallTimeSet(FreefallTimeDialog dialog, int freefallTime)
		{
			updateFreefallTime(freefallTime);
		}
	};
	private OnNumberSetListener cutawaySetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateCutaways(number);
		}
	};
	private OnNumberSetListener exitAltitudeSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateExitAltitude(number);
		}
	};
	private OnNumberSetListener deploymentAltitudeSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateDeploymentAltitude(number);
		}
	};
	private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener()
	{
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked)
		{
			handleUnitOfMeasureSelection((CheckBox)buttonView, isChecked);	
		}
	};

	@Override 
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		overridePendingTransition(R.anim.fadein,
                R.anim.hold);
		
		setContentView(R.layout.settings_view);
		
		initializeUI();
	}
	
	private void initializeUI()
	{
		// init header	
		if (this.findViewById(R.id.tabletLayout) != null)
		{
			InterfaceManager.getInstance().configureTabletUI(this, 
					R.string.settings_header);
		}
		else
		{
			InterfaceManager.getInstance().configurePhoneUI(this, 
					R.string.settings_header);
		}
		
		TextView freefallTimeField = (TextView) findViewById(R.id.SettingsFreefallTimeField);
		freefallTimeField.setOnClickListener(freefallTimeEditListener);

		TextView cutawayField = (TextView) findViewById(R.id.SettingsCutawaysField);
		cutawayField.setOnClickListener(cutawayEditListener);
		
		TextView exitAltField = (TextView) findViewById(R.id.SettingsExitAltitudeField);
		exitAltField.setOnClickListener(exitAltitudeEditListener);
		
		TextView deplAltField = (TextView) findViewById(R.id.SettingsDeploymentAltitude);
		deplAltField.setOnClickListener(deploymentAltitudeEditListener);
	
		CheckBox usUnits = (CheckBox) findViewById(R.id.SettingsUSCheckBox);
		CheckBox metricUnits = (CheckBox) findViewById(R.id.SettingsMetricCheckBox);
		
		// update uoms
		UnitOfMeasure uom = settingsRepository.getSettings().getUnitOfMeasure();
		usUnits.setChecked(uom == UnitOfMeasure.US);
		metricUnits.setChecked(uom == UnitOfMeasure.Metric);
		
		usUnits.setOnCheckedChangeListener(checkedChangeListener);
		metricUnits.setOnCheckedChangeListener(checkedChangeListener);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
	
		// init field values
		updateHistoryUI();
		updateAltitudeUI();
	}
	
	private void showFreefallTimeDialog()
	{
		// init dialog
		LogbookHistory history = historyRepository.getHistory();
		FreefallTimeDialog dialog = new FreefallTimeDialog(
				new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog),
				history.getFreefallTime(),
				freefallTimeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void showCutawayDialog()
	{
		// init dialog
		LogbookHistory history = historyRepository.getHistory();
		NumberDialog dialog = new NumberDialog(
				new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog),
				R.string.settings_cutaways_label,
				history.getCutaways(),
				cutawaySetListener);
		// show dialog
		dialog.show();
	}
	
	private void showExitAltitudeDialog()
	{
		// init dialog
		int exitAltitude = settingsRepository.getSettings().getExitAltitude();
		NumberDialog dialog = new NumberDialog(
				new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog),
				R.string.settings_default_exit_altitude_label,
				exitAltitude,
				exitAltitudeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void showDeploymentAltitudeDialog()
	{
		// init dialog
		int deploymentAltitude = settingsRepository.getSettings().getDeploymentAltitude();
		NumberDialog dialog = new NumberDialog(
				new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog),
				R.string.settings_default_deployment_altitude_label,
				deploymentAltitude,
				deploymentAltitudeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void updateFreefallTime(int freefallTime)
	{
		// update history
		LogbookHistory history = historyRepository.getHistory();
		history.setFreefallTime(freefallTime);
		historyRepository.updateHistory(history);
		
		// update UI
		updateHistoryUI();
	}
	
	private void updateHistoryUI()
	{
		// get history
		LogbookHistory history = historyRepository.getHistory();
		int freefallTime = history.getFreefallTime();
		
		// format
		int hours = freefallTime / 3600;
		int secondsLeftFromHours = freefallTime % 3600;
		int minutes = secondsLeftFromHours / 60;
		int seconds = secondsLeftFromHours % 60;
		// freefall time
		TextView freefallTimeField = (TextView) findViewById(R.id.SettingsFreefallTimeField);
		String ffTimeString = MessageFormat.format(
				getString(R.string.freefall_time_hms_format), hours, minutes, seconds);
		freefallTimeField.setText(ffTimeString);
		// cutaways
		TextView cutawayField = (TextView) findViewById(R.id.SettingsCutawaysField);
		cutawayField.setText(FormatUtility.toNumericString(history.getCutaways()));
	}
	
	private void updateCutaways(int cutaways)
	{
		// update history
		LogbookHistory history = historyRepository.getHistory();
		history.setCutaways(cutaways);
		historyRepository.updateHistory(history);
		
		// update UI
		updateHistoryUI();
	}
	
	private void updateExitAltitude(int altitude)
	{
		// update settings
		Settings settings = settingsRepository.getSettings();
		settings.setExitAltitude(altitude);
		settingsRepository.updateSettings(settings);
		
		// update UI
		updateAltitudeUI();
	}
	
	private void updateDeploymentAltitude(int altitude)
	{
		// update settings
		Settings settings = settingsRepository.getSettings();
		settings.setDeploymentAltitude(altitude);
		settingsRepository.updateSettings(settings);
		
		// update UI
		updateAltitudeUI();
	}
	
	private void updateAltitudeUI()
	{
		Settings settings = settingsRepository.getSettings();
		// exit altitude
		TextView exitAltField = (TextView) findViewById(R.id.SettingsExitAltitudeField);
		exitAltField.setText(FormatUtility.toNumericString(settings.getExitAltitude()));
		// deplyment altitude
		TextView deplAltField = (TextView) findViewById(R.id.SettingsDeploymentAltitude);
		deplAltField.setText(FormatUtility.toNumericString(settings.getDeploymentAltitude()));
	}

	private void handleUnitOfMeasureSelection(CheckBox checkBox, boolean isChecked)
	{
		// get checkboxes
		CheckBox usUnits = (CheckBox) findViewById(R.id.SettingsUSCheckBox);
		CheckBox metricUnits = (CheckBox) findViewById(R.id.SettingsMetricCheckBox);
		
		// get settings
		Settings settings = settingsRepository.getSettings();
		
		if (checkBox == usUnits && isChecked)
		{
			// clear metric
			metricUnits.setChecked(false);
			// update settings
			settings.setUnitOfMeasure(UnitOfMeasure.US);
		}
		else if (checkBox == metricUnits && isChecked)
		{
			// clear us
			usUnits.setChecked(false);
			// update settings
			settings.setUnitOfMeasure(UnitOfMeasure.Metric);
		}
		
		// save settings
		settingsRepository.updateSettings(settings);
	}
	
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_back:
			close();
        	return true;
        
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
    	overridePendingTransition(R.anim.hold,
                R.anim.fadeout);
	}
}
